<template>
    <div>
        <el-main>
            <el-button type="success" round @click="dialogFormVisible=true">添加新的游戏规格</el-button>
            &emsp;
            <el-select v-model="gameIdToNameForSearch" filterable placeholder="可选择游戏名进行筛选">
                <el-option
                    v-for="item in allGameDataForSearch"
                    :key="item.id"
                    :label="item.fullName"
                    :value="item.id">
                </el-option>
            </el-select>
            <el-table :data="tableData.records">
                <el-table-column label="游戏图" width="240">
                    <template slot-scope="scope">
                        <el-avatar icon="el-icon-user-solid" shape="square" :src="scope.row.gamePhoto" :key="scope.row.gamePhoto"></el-avatar>
                    </template>
                </el-table-column>
                <el-table-column label="游戏名" width="120" :formatter="getGameName">
                </el-table-column>
                <el-table-column label="游戏规格" width="120" :formatter="getSpecificationName">
                </el-table-column>
                <el-table-column label="是否上架" width="120" :formatter="isSell">
                </el-table-column>
                <el-table-column prop="gameValue" label="价格＄" width="120">
                </el-table-column>
                <el-table-column prop="number" label="现有库存量" width="120">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-button type="primary" icon="el-icon-edit" circle @click.native.prevent="updateById(scope.row)"></el-button>
                        <el-dialog title="游戏具体版本信息" :visible.sync="dialogFormVisible"  close-on-press-escape :before-close="clearUpdateData">
                        <el-form :model="gameSpecification">
                            <el-form-item label="游戏名" :label-width="formLabelWidth">  
                                <el-select v-model="gameIdToName" filterable placeholder="请选择">
                                    <el-option
                                        v-for="item in allGameData"
                                        :key="item.id"
                                        :label="item.fullName"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="游戏规格" :label-width="formLabelWidth">  
                                <el-select v-model="specificationToName" filterable placeholder="请选择">
                                    <el-option
                                        v-for="item in allSpecification"
                                        :key="item.specification"
                                        :label="item.name"
                                        :value="item.specification">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否上架" :label-width="formLabelWidth">
                                <el-switch
                                    v-model="gameSpecification.putaway"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949">
                                </el-switch>
                            </el-form-item>
                            <el-form-item label="游戏图片" :label-width="formLabelWidth">
                                <el-upload
                                    name="photo"
                                    class="avatar-uploader"
                                    action="http://localhost/graduateprogram/game-specification/uploadPhoto"
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload">
                                    <img v-if="gameSpecification.gamePhoto" :src="gameSpecification.gamePhoto" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                            <el-form-item label="游戏价格＄" :label-width="formLabelWidth">
                                <el-input v-model="gameSpecification.gameValue" autocomplete="off" type="number" min="0"></el-input>
                            </el-form-item>
                            <el-form-item label="库存数量" :label-width="formLabelWidth">
                                <el-input v-model="gameSpecification.number" autocomplete="off" type="number" min="0"></el-input>
                            </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="clearUpdateData">取 消</el-button>
                            <el-button type="primary" @click="updateManagerByIdArAddNew" :loading="uploading">确 定</el-button>
                        </div>
                        </el-dialog>
                        &ensp;   
                        <!-- 导入激活码 -->
                        <el-button type="success" icon="el-icon-download" circle @click.native.prevent="addKeys(scope.row)">进货<i class="el-icon-upload el-icon--right"></i></el-button>
                        <el-dialog title="导入激活码（进货）" :visible.sync="dialogFileVisible" width="15%">
                            <el-button @click="downloadTemplate">下载模板</el-button>
                            <br/><br/>
                            <el-upload
                                name="keysExcel"
                                class="upload-demo"
                                action="http://localhost/graduateprogram/keys/ayalysisKeysData"
                                :on-success="uploadExcelSuccess"
                                :before-upload="beforeExcelUpload">
                                <el-button size="small" type="primary" :loading="uploading">点击上传</el-button>
                                <div slot="tip" class="el-upload__tip">只能上传xlsx文件，且不超过1000kb，且每次导入都需要重新下载模板，切不可偷懒</div>
                            </el-upload>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="dialogFileVisible = false" :loading="uploading">取 消</el-button>
                                <el-button type="primary" @click="dialogFileVisible = false" :loading="uploading">确 定</el-button>
                            </span>
                        </el-dialog>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <common-footer :pageData="tableData" ref="footData"></common-footer>
    </div>
</template>
  
<script>
import CommonFooter from '@/components/CommonFooter.vue';
import axios from 'axios'
export default {
    name:"GameSpecification",
    props:["page","pageSize"],
    components:{CommonFooter},
    data() {
        return{
            tableData:{},
            gameData:[],
            allGameData:[],
            allGameDataForSearch:[],
            gameIdForSearch:'',
            allSpecification:[
                {
                    specification:"T",
                    name:'标准版',
                },
                {
                    specification:"S",
                    name:'导剪版',
                },
                {
                    specification:"G",
                    name:'黄金版',
                },
                {
                    specification:"L",
                    name:'终极版',
                },
            ],
            formLabelWidth: '120px',
            uploading: false,
            dialogFormVisible:false,//修改/新增页面开关
            dialogFileVisible:false,//导入/上传激活码文件开关
            gameSpecification:{
                id:'',
                gameId:'',
                specification:'',
                putaway:false,
                gamePhoto:'',
                gameValue:'',
                number:0,
            },
            downloadId:'',
            downloadNumber:'',
        }
    },
    mounted() {
        this.$refs.footData.$on('pageSize',this.getPageSize);//接收子组件分页栏的每页显示条目数
        this.$refs.footData.$on('currentPage',this.getCurrentPage);//接收子组件分页栏的数据
        axios.get(`/game-specification/getPage?page=${this.page}&pageSize=${this.pageSize}`).then(
            response=>{
                this.tableData=response.data.data;
            },
            error=>{
                console.log("请求失败。原因是",error.message);
            }
        );
        axios.get('/games/getAll').then(
            response=>{
                this.allGameData=response.data.data;
                this.allGameDataForSearch=[].concat(this.allGameData)
                this.allGameDataForSearch.unshift({
                    id:'',
                    simpleName:'',
                    fullName:'->不进行游戏筛选',
                    classesId:'',
                });
            }
        )
    },
    methods:{
        getGameName(row){//匹配游戏名并展示
            var gn="";
            this.allGameData.forEach((game)=>{
                if(row.gameId===game.id){
                    gn=game.fullName;
                    return
                }
            })
            return gn;
        },
        getSpecificationName(row){//处理版本显示
            if(row.specification==="T"){
                return "标准版";
            }else if(row.specification==="S"){
                return "导剪版";
            }else if(row.specification==="G"){
                return "黄金版";
            }else if(row.specification==="L"){
                return "终极版";
            }else{
                return "规格不详";
            }
        },
        isSell(row){//处理上下架显示
            if(row.putaway){
                return "已上架";
            }else{
                return "下架了";
            }
        },
        getPageSize(pagesize){//改变每页数据量，触发监控属性发请求
            this.tableData.size=pagesize;
        },
        getCurrentPage(currentpage){//改变当前页，触发监控属性发请求
            this.tableData.current=currentpage;
        },
        updataPageData(){//增删改后更新页面，模糊查询，改变每页个数，翻页等功能
            axios.get(`/game-specification/getPage?page=${this.tableData.current}&pageSize=${this.tableData.size}&gameId=${this.gameIdForSearch}`).then(
            response=>{
                this.tableData=response.data.data;
                this.gameSpecification={
                    id:'',
                    gameId:'',
                    specification:'',
                    putaway:false,
                    gamePhoto:'',
                    gameValue:'',
                    number:0,
                }
            },
            error=>{
                console.log("请求失败。原因是",error.message);
            });
        },
        handleAvatarSuccess(res) {//图片上传成功后返回地址
            this.gameSpecification.gamePhoto=res.data;
            this.uploading=false;
        },
        beforeAvatarUpload(file) {//图片上传之前进行校验
            this.uploading=true;
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
                this.uploading=false;
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                this.uploading=false;
            }
            return isJPG && isLt2M;
        },
        updateById(val){//进入修改页面
            this.dialogFormVisible = true;//开启信息页面
            this.gameSpecification.id=val.id;
            this.gameSpecification.gameId=val.gameId;
            this.gameSpecification.specification=val.specification;
            this.gameSpecification.putaway=val.putaway;
            this.gameSpecification.gamePhoto=val.gamePhoto;
            this.gameSpecification.gameValue=val.gameValue;
            this.gameSpecification.number=val.number;
        },
        updateManagerByIdArAddNew(){//发请求进行修改或者新添
            this.dialogFormVisible = false;
            if(this.gameSpecification.id===''){//没有id则为新增
                axios(
                    {
                        method:'post',
                        url:'/game-specification/addNew',
                        data:this.gameSpecification
                    }
                ).then(
                response=>{
                    response;
                    this.updataPageData();
                    alert('添加新的游戏规格成功');
                });
            }else{//有id则为修改
                axios(
                    {
                        method:'post',
                        url:'/game-specification/updateById',
                        data:this.gameSpecification,
                    }
                ).then(
                response=>{
                    response;
                    this.updataPageData();
                    alert('游戏规格修改成功');
                });
            }       
        },
        clearUpdateData(){//关闭对话框时清空表单数据
            this.dialogFormVisible = false;
            this.gameSpecification={
                id:'',
                gameId:'',
                specification:'',
                putaway:false,
                gamePhoto:'',
                gameValue:'',
                number:0,
            }
        },
        addKeys(val){
            this.downloadId=val.id;
            this.downloadNumber=val.number;
            this.dialogFileVisible=true;
        },
        downloadTemplate(){//下载激活码表模板文件
            let params=new URLSearchParams();
            params.append('id',this.downloadId);
            params.append('number',this.downloadNumber);
            axios(
                {
                    method:'get',
                    url:'/game-specification/downloadExcelTemplate',
                    params,
                    responseType:'blob'
                }
            ).then(({data}) => {            
                let objectUrl = data
                // 这里的type和后端请求携带的 ContentType 相对应
                const blob = new Blob([data], {type:'application/vnd.ms-excel;charset=utf-8'});
                objectUrl = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = objectUrl;
                // 定义文件名
                a.download ="激活码导入模板.xlsx";
                a.click();
                a.remove();
                URL.revokeObjectURL(objectUrl)
          });
        },
        beforeExcelUpload(file){//激活码表上传前校验
            this.uploading=true;
            const isExcel=file.type==='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            const isLt1M=file.size/1024/1024<=1;
            if(!isExcel){
                this.$message.error("上传文件只能是xlsx格式");
                this.uploading=false;
            }
            if(!isLt1M){
                this.$message.error("上传文件大小不能超过1MB");
                this.uploading=false;
            }
            return isExcel&&isLt1M;
        },
        uploadExcelSuccess(){//激活码表上传成功后
            this.uploading=false;
            this.updataPageData();
        }
    },
    watch:{
        'tableData.size':{
            handler(newValue,oldValue){
                if(oldValue!==undefined){
                this.updataPageData();
                }
            }
        },
        'tableData.current':{
            handler(newValue,oldValue){
                if(oldValue!==undefined){
                this.updataPageData();
                }
            }
        },
        gameIdForSearch(){
            if(this.tableData.current===1){
                this.updataPageData();
            }else{
                this.tableData.current=1;
            }
        }
    },
    computed:{
        gameIdToName:{//游戏名游戏id匹配
            get(){
                var gn="";
                this.allGameData.forEach((game)=>{
                    if(this.gameSpecification.gameId===game.id){
                        gn=game.fullName;
                        return
                    }
                })
                return gn;
            },
            set(value){
                this.gameSpecification.gameId=value;
            }
        },
        specificationToName:{//规格名匹配
            get(){
                if(this.gameSpecification.specification==="T"){
                    return "标准版";
                }else if(this.gameSpecification.specification==="S"){
                    return "导剪版";
                }else if(this.gameSpecification.specification==="G"){
                    return "黄金版";
                }else if(this.gameSpecification.specification==="L"){
                    return "终极版";
                }else{
                    return "规格不详";
                }
            },
            set(value){
                this.gameSpecification.specification=value;
            }
        },
        gameIdToNameForSearch:{
            get(){
                var gn="";
                this.allGameDataForSearch.forEach((game)=>{
                    if(this.gameIdForSearch===game.id){
                        gn=game.fullName;
                        return
                    }
                })
                return gn;
            },
            set(value){
                this.gameIdForSearch=value;
            }
        }
    }
}
</script>
  
<style scoped>
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>